package org.chickymate.server.controller.command.json;

import java.util.List;

import org.chickymate.server.controller.RequestWrapper;
import org.chickymate.server.model.Comment;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class GetCommentsCommand extends JSONAbstractCommand {

	@Override
	protected Object execute(RequestWrapper request) {
		return getCommentDao().getComments(request.getUrl());
	}

	@Override
	protected JSONObject resultToJson(Object object) throws JSONException {
		return this.fromListToJsonObject((List<Comment>)object);
	}

	private JSONObject fromListToJsonObject(List<Comment> comments) throws JSONException {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("data", this.fromListToJSonArray(comments));
		return jsonObject;
	}

	private JSONArray fromListToJSonArray(List<Comment> comments) throws JSONException {
		JSONArray jsonArray = new JSONArray();
		for (Comment comment : comments) {
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("id", comment.getId().longValue());
			jsonObject.put("createdDate", comment.getCreatedDate());			
			jsonObject.put("text", comment.getText());
			jsonObject.put("negativeVotes", comment.getNegativeVotes());
			jsonObject.put("positiveVotes", comment.getPositiveVotes());
			jsonArray.put(jsonObject);
		}
		return jsonArray;
	}

}
